﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Windows;//rect, add windowbase.dll .NET
using System.Windows.Media;// media,add presentationcore.dll .NET
using System.Windows.Media.Imaging;//Rendertargetbitmap. add presentationcore.dll .NET
//add System.Xaml dll .NET to use Uri

namespace TrippleVideoControl
{
    public partial class VideoControl : UserControl
    {        
        public string[] FileNames { get; set; }
        public int m1;
        public int ordervideo = 1;
        public string Savefilepath;
                
        public VideoControl()
        {
            InitializeComponent();
            ax1.settings.autoStart = false;
            ax2.settings.autoStart = false;
            ax3.settings.autoStart = false;
            //ax1.settings.volume = VOLUMEADJ.Value;
            //ax2.settings.volume = VOLUMEADJ.Value;
            //ax3.settings.volume = VOLUMEADJ.Value;
           // timer2.Start();
            //timer2.Enabled = false;
            SpeedCtl.Enabled = false;
            
                    }

        #region Order video display
        public void Swap(ref int a)
        {
            Stop();
            switch (a)
            {
                case 0:
                    SetFileName(FileNames[0], FileNames[1], FileNames[2]);
                    a = 1;
                    break;
                case 1:
                    SetFileName(FileNames[1], FileNames[0], FileNames[2]);
                    a = 2;
                    break;
                case 2:
                    SetFileName(FileNames[0], FileNames[2], FileNames[1]);
                    a = 3;
                    break;
                case 3:
                    SetFileName(FileNames[2], FileNames[1], FileNames[0]);
                    a = 0;
                    break;
            }
            Play();
        } 
        #endregion

        #region Order video button
        private void ORDER_Click(object sender, EventArgs e)
        {
            Swap(ref ordervideo);
        }
        #endregion

        #region Set filename of axwindowmediaplayer
        public void SetFileName(string str1, string str2, string str3)
        {
            ax1.URL = str1;
            ax2.URL = str2;
            ax3.URL = str3;

        }
        #endregion

        #region Get path of axwindowmediaplayer
        public void Getpath()
        {
            ax1.URL = FileNames[0];
            ax2.URL = FileNames[1];
            ax3.URL = FileNames[2];

        }  
        #endregion

        #region Functions for control axwindowmediaplayer
        public void Play()
        {
            ax1.Ctlcontrols.play();
            //Thread.Sleep(50);
            ax2.Ctlcontrols.play();
            //Thread.Sleep(50);
            ax3.Ctlcontrols.play();
            //Thread.Sleep(50);
        }
        public void Pause()
        {
            ax1.Ctlcontrols.pause();
            ax2.Ctlcontrols.pause();
            ax3.Ctlcontrols.pause();
        }
        public void Stop()
        {
            ax1.Ctlcontrols.stop();
            ax2.Ctlcontrols.stop();
            ax3.Ctlcontrols.stop();
        }
        public void Setmute()
        {
            if (Mute.Checked == true)
            {
                ax1.settings.mute = true;
                ax2.settings.mute = true;
                ax3.settings.mute = true;
                VOLUMEADJ.Enabled = false;
            }
            else
            {
                ax1.settings.mute = false;
                ax2.settings.mute = false;
                ax3.settings.mute = false;
                VOLUMEADJ.Enabled = true;
            }

        }
        public void Volumeset()
        {
            ax1.settings.volume = VOLUMEADJ.Value;
            ax2.settings.volume = VOLUMEADJ.Value;
            ax3.settings.volume = VOLUMEADJ.Value;
        }
        
        public void Setpositon(double videopostion)
        {
            ax1.Ctlcontrols.currentPosition = videopostion;
            ax2.Ctlcontrols.currentPosition = videopostion;
            ax3.Ctlcontrols.currentPosition = videopostion;
        } 
        #endregion

        #region Play, pause, stop button 
        private void PLAYBTN_Click(object sender, EventArgs e)
        {
            try
            {
                //if (ax1.playState == WMPLib.WMPPlayState.wmppsPaused)
                //{
                //    SEEKBAR.Value = (int)ax1.Ctlcontrols.currentPosition;
                //}
                //else { SEEKBAR.Value = 0; }
                SpeedCtl.SelectedIndex = 1;
                SpeedCtl.Enabled = true;
                Play();

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            PLAYBTN.Enabled = false;
        }
        private void STOPBTN_Click(object sender, EventArgs e)
        {
            Stop();
            PLAYBTN.Enabled = true;
        }

        private void PAUSEBTN_Click(object sender, EventArgs e)
        {
            Pause();
            PLAYBTN.Enabled = true;
            SpeedCtl.Enabled = false;
        }
        
        #endregion

        #region axwindowmediaplayer play state change
        private void ax1playstate(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            if ((ax1.playState == WMPLib.WMPPlayState.wmppsPlaying))
            //if ((ax1.playState == WMPLib.WMPPlayState.wmppsPlaying) &&
            //    ((ax2.playState == WMPLib.WMPPlayState.wmppsPlaying)) &&
            //    (ax3.playState == WMPLib.WMPPlayState.wmppsPlaying))
            {
                if (timer2.Enabled == false)
                {
                    timer2.Enabled = true;
                }

                SEEKBAR.Maximum = Math.Max(Math.Max((int)ax1.Ctlcontrols.currentItem.duration,
                                             (int)ax2.Ctlcontrols.currentItem.duration),
                                             (int)ax3.Ctlcontrols.currentItem.duration);
                if ((int)ax1.Ctlcontrols.currentItem.duration == SEEKBAR.Maximum)
                {
                    m1 = 1;
                    label1.Text = ax1.currentMedia.durationString;

                }
                if ((int)ax2.Ctlcontrols.currentItem.duration == SEEKBAR.Maximum)
                {
                    m1 = 2;
                    label1.Text = ax2.currentMedia.durationString;
                }
                if ((int)ax3.Ctlcontrols.currentItem.duration == SEEKBAR.Maximum)
                {
                    m1 = 3;
                    label1.Text = ax3.currentMedia.durationString;
                }
                PLAYBTN.Enabled = false;
                SpeedCtl.Enabled = true;
                Volumeset();
            }
            if ((ax1.playState == WMPLib.WMPPlayState.wmppsStopped))
            //if ((ax1.playState == WMPLib.WMPPlayState.wmppsStopped) &&
            //    (ax2.playState == WMPLib.WMPPlayState.wmppsStopped) &&
            //    (ax2.playState == WMPLib.WMPPlayState.wmppsStopped))
            {
                SEEKBAR.Value = 0;
                SpeedCtl.SelectedIndex = 1;
                SpeedCtl.Enabled = false;
                label1.Text = "00:00:00";
                label2.Text = "00:00:00";
                m1 = 0;
                PLAYBTN.Enabled = true;
                timer2.Enabled = false;
            }

        }

        private void ax2playstate(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            if ((ax2.playState == WMPLib.WMPPlayState.wmppsPlaying))
            //if ((ax1.playState == WMPLib.WMPPlayState.wmppsPlaying) &&
            //    (ax2.playState == WMPLib.WMPPlayState.wmppsPlaying) &&
            //    (ax3.playState == WMPLib.WMPPlayState.wmppsPlaying))
            {
                if (timer2.Enabled == false)
                {
                    timer2.Enabled = true;
                }
                SEEKBAR.Maximum = Math.Max(Math.Max((int)ax1.Ctlcontrols.currentItem.duration,
                                             (int)ax2.Ctlcontrols.currentItem.duration),
                                             (int)ax3.Ctlcontrols.currentItem.duration);
                if ((int)ax1.Ctlcontrols.currentItem.duration == SEEKBAR.Maximum)
                {
                    m1 = 1;
                    label1.Text = ax1.currentMedia.durationString;
                }
                if ((int)ax2.Ctlcontrols.currentItem.duration == SEEKBAR.Maximum)
                {
                    m1 = 2;
                    label1.Text = ax2.currentMedia.durationString;
                }
                if ((int)ax3.Ctlcontrols.currentItem.duration == SEEKBAR.Maximum)
                {
                    m1 = 3;
                    label1.Text = ax3.currentMedia.durationString;
                }
                PLAYBTN.Enabled = false;
                SpeedCtl.Enabled = true;
                Volumeset();
            }
            if ((ax2.playState == WMPLib.WMPPlayState.wmppsStopped))
            //if ((ax1.playState == WMPLib.WMPPlayState.wmppsStopped) &&
            //    (ax2.playState == WMPLib.WMPPlayState.wmppsStopped) &&
            //    (ax2.playState == WMPLib.WMPPlayState.wmppsStopped))
            {
                SEEKBAR.Value = 0;
                SpeedCtl.SelectedIndex = 1;
                SpeedCtl.Enabled = false;
                label1.Text = "00:00:00";
                label2.Text = "00:00:00";
                m1 = 0;
                PLAYBTN.Enabled = true;
                timer2.Enabled = false;
            }

        }

        private void ax3playstate(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            if ((ax3.playState == WMPLib.WMPPlayState.wmppsPlaying))
            //if ((ax1.playState == WMPLib.WMPPlayState.wmppsPlaying) &&
            //    (ax2.playState == WMPLib.WMPPlayState.wmppsPlaying) &&
            //    (ax3.playState == WMPLib.WMPPlayState.wmppsPlaying))
            {
                if (timer2.Enabled == false)
                {
                    timer2.Enabled = true;
                }
                SEEKBAR.Maximum = Math.Max(Math.Max((int)ax1.Ctlcontrols.currentItem.duration,
                                             (int)ax2.Ctlcontrols.currentItem.duration),
                                             (int)ax3.Ctlcontrols.currentItem.duration);
                if ((int)ax1.Ctlcontrols.currentItem.duration == SEEKBAR.Maximum)
                {
                    m1 = 1;
                    label1.Text = ax1.currentMedia.durationString;
                }
                if ((int)ax2.Ctlcontrols.currentItem.duration == SEEKBAR.Maximum)
                {
                    m1 = 2;
                    label1.Text = ax2.currentMedia.durationString;
                }
                if ((int)ax3.Ctlcontrols.currentItem.duration == SEEKBAR.Maximum)
                {
                    m1 = 3;
                    label1.Text = ax3.currentMedia.durationString;
                }
                PLAYBTN.Enabled = false;
                SpeedCtl.Enabled = true;
                Volumeset();
            }
            if ((ax3.playState == WMPLib.WMPPlayState.wmppsStopped))
            //if ((ax1.playState == WMPLib.WMPPlayState.wmppsStopped) &&
            //    (ax2.playState == WMPLib.WMPPlayState.wmppsStopped) &&
            //    (ax2.playState == WMPLib.WMPPlayState.wmppsStopped))
            {
                SEEKBAR.Value = 0;
                SpeedCtl.SelectedIndex = 1;
                SpeedCtl.Enabled = false;
                label1.Text = "00:00:00";
                label2.Text = "00:00:00";
                m1 = 0;
                PLAYBTN.Enabled = true;
                timer2.Enabled = false;
            }

        } 
        #endregion       

        #region Use timer to update seekbar
        private void timer2_Tick(object sender, EventArgs e)
        {
            switch (m1)
            {
                case 1:
                    SEEKBAR.Value = (int)ax1.Ctlcontrols.currentPosition;
                    label2.Text = ax1.Ctlcontrols.currentPositionString;
                    break;
                case 2:
                    SEEKBAR.Value = (int)ax2.Ctlcontrols.currentPosition;
                    label2.Text = ax2.Ctlcontrols.currentPositionString;
                    break;
                case 3:
                    SEEKBAR.Value = (int)ax3.Ctlcontrols.currentPosition;
                    label2.Text = ax3.Ctlcontrols.currentPositionString;
                    break;
            }
            Setmute();
            //for fullscreen exit because still not processed the pause state when exit full screen
            //Maybe will disable control of axwindowmediaplayer in future
            //if ((ax1.playState == WMPLib.WMPPlayState.wmppsPaused) &&
            //        ((ax2.playState == WMPLib.WMPPlayState.wmppsPlaying) ||
            //        (ax2.playState == WMPLib.WMPPlayState.wmppsPlaying)))
            //{
            //    ax1.Ctlcontrols.play();
            //}
            //if ((ax2.playState == WMPLib.WMPPlayState.wmppsPaused) &&
            //        ((ax1.playState == WMPLib.WMPPlayState.wmppsPlaying) ||
            //        (ax3.playState == WMPLib.WMPPlayState.wmppsPlaying)))
            //{
            //    ax2.Ctlcontrols.play();
            //}
            //if ((ax3.playState == WMPLib.WMPPlayState.wmppsPaused) &&
            //        ((ax1.playState == WMPLib.WMPPlayState.wmppsPlaying) ||
            //        (ax2.playState == WMPLib.WMPPlayState.wmppsPlaying)))
            //{
            //    ax3.Ctlcontrols.play();
            //}

        }
        #endregion       

        #region Setmute check, speed control, volume and seek bar adjust
        private void VOLUMEADJ_Scroll(object sender, EventArgs e)
        {
            Volumeset();
            //ax1.settings.volume = VOLUMEADJ.Value;
            //ax2.settings.volume = VOLUMEADJ.Value;
            //ax3.settings.volume = VOLUMEADJ.Value;
        }

        private void SEEKBAR_Scroll(object sender, EventArgs e)
        {
            if ((ax1.playState == WMPLib.WMPPlayState.wmppsPlaying) ||
             (ax2.playState == WMPLib.WMPPlayState.wmppsPlaying) ||
             (ax3.playState == WMPLib.WMPPlayState.wmppsPlaying))
            {
                ax1.Ctlcontrols.currentPosition = SEEKBAR.Value;
                ax2.Ctlcontrols.currentPosition = SEEKBAR.Value;
                ax3.Ctlcontrols.currentPosition = SEEKBAR.Value;

            }

        }
        private void MuteState(object sender, EventArgs e)
        {
            Setmute();
        }
        private void Speed(object sender, EventArgs e)
        {
            if (ax1.settings.get_isAvailable("Rate"))
            {
                ax1.settings.rate = double.Parse(SpeedCtl.SelectedItem.ToString());
                ax2.settings.rate = double.Parse(SpeedCtl.SelectedItem.ToString());
                ax3.settings.rate = double.Parse(SpeedCtl.SelectedItem.ToString());
            }
        }       

        #endregion

        #region Grab button fuction
        private RenderTargetBitmap bmp1 = null;
        private RenderTargetBitmap bmp2 = null;
        private RenderTargetBitmap bmp3 = null;
        private void GRAB_Click(object sender, EventArgs e)
        {
            PLAYBTN.Enabled = true;
            Pause();
            if (!(string.IsNullOrEmpty(ax1.URL) && string.IsNullOrEmpty(ax2.URL) && string.IsNullOrEmpty(ax3.URL)))
            {


                MediaPlayer mediaPlayer1 = new MediaPlayer();
                MediaPlayer mediaPlayer2 = new MediaPlayer();
                MediaPlayer mediaPlayer3 = new MediaPlayer();

                mediaPlayer1.MediaOpened += new EventHandler(mediaplayer1_OpenMedia);
                mediaPlayer1.ScrubbingEnabled = true;
                mediaPlayer1.Open(new Uri(ax1.URL));//(@"E:\Relax\FILM\Xeom.FLV"));
                mediaPlayer1.Position = TimeSpan.FromSeconds(ax1.Ctlcontrols.currentPosition);//TimeSpan.FromSeconds(2);

                mediaPlayer2.MediaOpened += new EventHandler(mediaplayer2_OpenMedia);
                mediaPlayer2.ScrubbingEnabled = true;
                mediaPlayer2.Open(new Uri(ax2.URL));//(@"E:\Relax\FILM\Xeom.FLV"));
                mediaPlayer2.Position = TimeSpan.FromSeconds(ax2.Ctlcontrols.currentPosition);//TimeSpan.FromSeconds(2);

                mediaPlayer3.MediaOpened += new EventHandler(mediaplayer3_OpenMedia);
                mediaPlayer3.ScrubbingEnabled = true;
                mediaPlayer3.Open(new Uri(ax3.URL));//(@"E:\Relax\FILM\Xeom.FLV"));
                mediaPlayer3.Position = TimeSpan.FromSeconds(ax3.Ctlcontrols.currentPosition);//TimeSpan.FromSeconds(2);


                saveFileDialog1.Filter = "Media Files|*.bmp;*.jpg;*.gif;";
                saveFileDialog1.FileName = Savefilepath;
                Boolean varexit=false;
                do
                {
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        Savefilepath = saveFileDialog1.FileName;

                        string Onlyfilename1;
                        string PathResult1;
                        Onlyfilename1 = Path.GetFileNameWithoutExtension(saveFileDialog1.FileName);
                        Onlyfilename1 = Onlyfilename1 + "_V1";
                        PathResult1 = Path.GetDirectoryName(saveFileDialog1.FileName);
                        PathResult1 = Path.Combine(PathResult1, Onlyfilename1 + Path.GetExtension(saveFileDialog1.FileName));

                        string Onlyfilename2;
                        string PathResult2;
                        Onlyfilename2 = Path.GetFileNameWithoutExtension(saveFileDialog1.FileName);
                        Onlyfilename2 = Onlyfilename2 + "_V2";
                        PathResult2 = Path.GetDirectoryName(saveFileDialog1.FileName);
                        PathResult2 = Path.Combine(PathResult2, Onlyfilename2 + Path.GetExtension(saveFileDialog1.FileName));

                        string Onlyfilename3;
                        string PathResult3;
                        Onlyfilename3 = Path.GetFileNameWithoutExtension(saveFileDialog1.FileName);
                        Onlyfilename3 = Onlyfilename3 + "_V3";
                        PathResult3 = Path.GetDirectoryName(saveFileDialog1.FileName);
                        PathResult3 = Path.Combine(PathResult3, Onlyfilename3 + Path.GetExtension(saveFileDialog1.FileName));

                        if ((File.Exists(PathResult1) == false)&&(File.Exists(PathResult2) == false)&&(File.Exists(PathResult3) == false))
                        {
                            if(File.Exists(ax1.URL))
                            {
                                JpegBitmapEncoder encoder1 = new JpegBitmapEncoder();
                                encoder1.QualityLevel = 100;
                                encoder1.Frames.Add(BitmapFrame.Create(bmp1));
                                //FileStream fileStream1= new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.ReadWrite);
                                FileStream fileStream1 = new FileStream(PathResult1, FileMode.Create, FileAccess.ReadWrite);
                                encoder1.Save(fileStream1);
                                fileStream1.Close();
                            }
                            if (File.Exists(ax2.URL))
                            {
                                JpegBitmapEncoder encoder2 = new JpegBitmapEncoder();
                                encoder2.QualityLevel = 100;
                                encoder2.Frames.Add(BitmapFrame.Create(bmp2));
                                FileStream fileStream2 = new FileStream(PathResult2, FileMode.Create, FileAccess.ReadWrite);
                                encoder2.Save(fileStream2);
                                fileStream2.Close();
                            }
                            if (File.Exists(ax3.URL))
                            {
                                JpegBitmapEncoder encoder3 = new JpegBitmapEncoder();
                                encoder3.QualityLevel = 100;
                                encoder3.Frames.Add(BitmapFrame.Create(bmp3));
                                FileStream fileStream3 = new FileStream(PathResult3, FileMode.Create, FileAccess.ReadWrite);
                                encoder3.Save(fileStream3);
                                fileStream3.Close();
                            }
                            varexit = true;
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show(Path.GetFileNameWithoutExtension(saveFileDialog1.FileName)
                                                                + "_Vx(x=1,2,3) file name already exist! Save another filename", "Confirm Save As",
                                                                MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
                            
                        }

                    }
                    else 
                    {
                        varexit = true;
                    }
                } while (!varexit);
                
            }

        }
        private void mediaplayer1_OpenMedia(object sender, EventArgs e)
        {

            MediaPlayer mediaPlayer1 = sender as MediaPlayer;

            DrawingVisual drawingVisual = new DrawingVisual();

            DrawingContext drawingContext = drawingVisual.RenderOpen();

            drawingContext.DrawVideo(mediaPlayer1, new Rect(0, 0, ax1.currentMedia.imageSourceWidth, ax1.currentMedia.imageSourceHeight));

            drawingContext.Close();

            bmp1 = new RenderTargetBitmap(ax1.currentMedia.imageSourceWidth, ax1.currentMedia.imageSourceHeight, 1 / 200, 1 / 200, PixelFormats.Pbgra32);

            bmp1.Render(drawingVisual);

        }
        private void mediaplayer2_OpenMedia(object sender, EventArgs e)
        {

            MediaPlayer mediaPlayer2 = sender as MediaPlayer;

            DrawingVisual drawingVisual = new DrawingVisual();

            DrawingContext drawingContext = drawingVisual.RenderOpen();

            drawingContext.DrawVideo(mediaPlayer2, new Rect(0, 0, ax2.currentMedia.imageSourceWidth, ax2.currentMedia.imageSourceHeight));

            drawingContext.Close();

            bmp2 = new RenderTargetBitmap(ax2.currentMedia.imageSourceWidth, ax2.currentMedia.imageSourceHeight, 1 / 200, 1 / 200, PixelFormats.Pbgra32);

            bmp2.Render(drawingVisual);
        }

        private void mediaplayer3_OpenMedia(object sender, EventArgs e)
        {

            MediaPlayer mediaPlayer3 = sender as MediaPlayer;

            DrawingVisual drawingVisual = new DrawingVisual();

            DrawingContext drawingContext = drawingVisual.RenderOpen();

            drawingContext.DrawVideo(mediaPlayer3, new Rect(0, 0, ax3.currentMedia.imageSourceWidth, ax3.currentMedia.imageSourceHeight));

            drawingContext.Close();

            bmp3 = new RenderTargetBitmap(ax3.currentMedia.imageSourceWidth, ax3.currentMedia.imageSourceHeight, 1 / 200, 1 / 200, PixelFormats.Pbgra32);

            bmp3.Render(drawingVisual);
        }

        #endregion   

      
    }  
}
